<template>
  <div class="text-recall">
    <el-skeleton :rows="5" animated v-if="loading" />
    <el-alert v-else-if="error" :title="error" type="error" show-icon :closable="false" />
    <div v-else>
      <MyHeaderInLesson :lesson="lesson" :moduleName="'课文回想'" />

      <AudioControls
        :current-index="currentSentenceIndex"
        :total-items="lesson.content.length"
        :is-playing="isPlaying"
        @previous="playPrevious"
        @toggle-playback="togglePlayback"
        @next="playNext"
        @speed-change="changeSpeed"
      />
      <TextRecallDisplay
        :isPlaying="isPlaying"
        :content="lesson.content"
        :current-index="currentSentenceIndex"
        :playing-index="playingSentenceIndex"
        @play-sentence="playSingleSentence"
      />
    </div>
  </div>
</template>

<script>
import TextRecallDisplay from '../components/text-study/TextRecallDisplay.vue'
import AudioControls from '../components/text-study/AudioControls.vue'
import { ElSkeleton, ElAlert, ElPageHeader, ElCheckbox, ElInputNumber } from 'element-plus'
import { lessonLoader } from '../mixins/lessonLoader.js'
import MyHeaderInLesson from '../components/layout/MyHeaderInLesson.vue'
import KeyboardAudio from '../utils/keyboardAudio.js'

export default {
  name: 'TextRecall',
  components: {
    TextRecallDisplay,
    AudioControls,
    ElSkeleton,
    ElAlert,
    ElPageHeader,
    ElCheckbox,
    ElInputNumber,
    MyHeaderInLesson
  },
  mixins: [lessonLoader],
  data() {
    return {
      currentSentenceIndex: 0,
      playingSentenceIndex: -1, // 正在播放的句子索引，用于高亮显示
      isPlaying: false,
      // 添加新的控制选项
      continuousReading: true,
      repeatSentence: false,
      repeatArticle: false,
      sentenceRepeatCount: 1,
      currentSentencePlayCount: 0,
      sentenceEndTime: 0,
      // Store state when playing a single sentence
      wasPlaying: false
    }
  },
  async mounted() {
    KeyboardAudio.register('Enter', this.togglePlayback)
    // 注册空格键
    KeyboardAudio.register(' ', this.togglePlayback)
    KeyboardAudio.register('ArrowLeft', this.playPrevious)
    KeyboardAudio.register('ArrowRight', this.playNext)
    const lessonId = this.$route.params.id
    await this.loadLesson(lessonId)

    // Check for sentence_id parameter and set current sentence index
    const sentenceId = this.$route.query.sentence_id
    if (sentenceId && !isNaN(sentenceId) && sentenceId > 0) {
      // Convert to 0-based index
      const index = parseInt(sentenceId) - 1
      // Make sure it's within bounds
      if (index < this.lesson.content.length) {
        this.currentSentenceIndex = index
      }
    }
  },
  beforeUnmount() {
    KeyboardAudio.destroy()
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }
  },
  methods: {
    playPrevious() {
      if (this.currentSentenceIndex > 0) {
        this.currentSentenceIndex--
        this.currentSentencePlayCount = 0 // 用户主动切换，重置计数
        this.playCurrentSentence()
      }
    },

    togglePlayback() {
      if (this.isPlaying) {
        this.pauseAudio()
      } else {
        this.currentSentencePlayCount = 0 // 用户主动播放，重置计数
        this.playCurrentSentence()
      }
    },

    playNext() {
      if (this.currentSentenceIndex < this.lesson.content.length - 1) {
        this.currentSentenceIndex++
        this.currentSentencePlayCount = 0 // 用户主动切换，重置计数
        this.playCurrentSentence()
      } else if (this.repeatArticle) {
        // 如果启用循环播放文章，则回到第一句
        this.currentSentenceIndex = 0
        this.currentSentencePlayCount = 0 // 用户主动切换，重置计数
        this.playCurrentSentence()
      }
    },

    playCurrentSentence() {
      if (!this.audio || this.lesson.content.length === 0) return

      const sentence = this.lesson.content[this.currentSentenceIndex]
      if (sentence.startTime !== undefined && sentence.endTime !== undefined) {
        this.audio.currentTime = sentence.startTime
        this.sentenceEndTime = sentence.endTime

        // 设置正在播放的句子索引，以便高亮显示英文文本
        this.playingSentenceIndex = this.currentSentenceIndex

        this.audio.play()
        this.isPlaying = true
      }
    },

    pauseAudio() {
      if (this.audio) {
        this.audio.pause()
      }
      this.isPlaying = false
      this.playingSentenceIndex = -1 // 重置高亮显示
    },

    onAudioTimeUpdate() {
      // 检查是否到达句子结束时间
      if (this.isPlaying && this.audio && this.audio.currentTime >= this.sentenceEndTime) {
        this.audio.pause()
        this.isPlaying = false
        this.onAudioEnded()
      }
    },

    onAudioEnded() {
      this.isPlaying = false
      this.playingSentenceIndex = -1 // 重置高亮显示

      // 如果启用了句子重复播放，或者启用了连续阅读并且设置了句子重复次数大于1
      if (
        (this.repeatSentence || (this.continuousReading && this.sentenceRepeatCount > 1)) &&
        this.currentSentencePlayCount < this.sentenceRepeatCount - 1
      ) {
        this.currentSentencePlayCount++
        this.$nextTick(() => {
          this.playCurrentSentence()
        })
        return
      }

      // 重置句子播放计数
      this.currentSentencePlayCount = 0

      // 如果启用连续阅读或到达文章末尾且启用了循环播放
      if (this.continuousReading || this.repeatArticle) {
        if (this.currentSentenceIndex < this.lesson.content.length - 1) {
          this.currentSentenceIndex++
          this.$nextTick(() => {
            this.playCurrentSentence()
          })
        } else if (this.repeatArticle) {
          // 如果启用循环播放文章，则回到第一句
          this.currentSentenceIndex = 0
          this.$nextTick(() => {
            this.playCurrentSentence()
          })
        }
      }
      // 如果不连续阅读且不循环文章，在句子结束时停止
      else if (!this.continuousReading && !this.repeatArticle) {
        // 保持在当前句子，等待用户操作
      }
    },

    changeSpeed(speed) {
      if (this.audio) {
        this.audio.playbackRate = speed
      }
    },

    // 连续阅读选项改变时的处理
    onContinuousReadingChange(value) {
      if (value) {
        // 启用连续阅读时，禁用句子循环播放
        this.repeatSentence = false
      }
    },

    // Play a single sentence when the button is clicked
    playSingleSentence(sentenceIndex) {
      // Store the current playback state
      this.wasPlaying = this.isPlaying

      // Pause current playback if playing
      if (this.isPlaying) {
        this.pauseAudio()
      }

      // Highlight the sentence being played
      this.currentSentenceIndex = sentenceIndex

      // Play the selected sentence
      this.playSentenceOnce(sentenceIndex)
    },

    // Play a sentence once and then restore previous state
    playSentenceOnce(sentenceIndex) {
      if (!this.audio || !this.lesson.content[sentenceIndex]) return

      const sentence = this.lesson.content[sentenceIndex]
      if (sentence.startTime !== undefined && sentence.endTime !== undefined) {
        const duration = sentence.endTime - sentence.startTime

        this.audio.currentTime = sentence.startTime
        // 设置正在播放的句子索引，以便高亮显示英文文本
        this.playingSentenceIndex = sentenceIndex
        this.audio.play()

        // Stop after the sentence duration
        setTimeout(() => {
          if (!this.audio) return
          this.audio.pause()
          this.playingSentenceIndex = -1 // 重置高亮显示

          // Resume previous playback if it was playing
          if (this.wasPlaying) {
            this.playCurrentSentence()
          }
        }, (duration * 1000) / (this.audio.playbackRate || 1))
      }
    }
  }
}
</script>

<style scoped>
.text-recall {
  margin: 0 auto;
  padding: 0px;
  max-width: 1200px;
}

.recall-options {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
  margin: 20px 0;
  flex-wrap: wrap;
}

.sentence-repeat-count {
  display: flex;
  align-items: center;
  gap: 5px;
}
</style>